package net.gxf.common.etf;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.gxf.common.util.CheckNetUtil;
import net.gxf.common.util.ConfigLoader;
import net.gxf.common.util.ExportFileUtil;
import net.gxf.common.util.StockQueryUtil;
import net.gxf.common.util.TimeFomartUtil;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


/**
 * 获得所有ETF
 * 
 * @author: maybe
 * 
 */
public class ETFTool {

	private final String DEFAULT_LOCATION = "C:/ETF/DATA/";// 默认的下载ETF位置

	private static Map<String, ETF> etfs = new HashMap<String, ETF>();

	/**
	 * 返回配置文件【etfURL.ini】中所有的ETF,包含上证和深证
	 * 
	 * @return
	 */
	public static Map<String, ETF> getETFs() {
		if (etfs.size() == 0)
			loadETFByIni();
		return etfs;
	}

	/**
	 * 以TXT格式文件保存
	 */
	public void saveETFAsTXT() {
		if (etfs.size() == 0)
			loadETFByIni();
		Iterator<String> iterator = etfs.keySet().iterator();
		while (iterator.hasNext()) {
			String next = iterator.next();
			ETF etf = etfs.get(next);
			List<StockETF> list = etf.getStockList();
			StringBuffer buffer = new StringBuffer();
			for (StockETF stockETF : list) {
				buffer.append(stockETF.getCode()).append("\t").append(stockETF.getName()).append("\t").append(stockETF.getNumber()).append("\t").append(stockETF.getWorth()).append("\r\n");
			}
			ExportFileUtil.ExportTxt(DEFAULT_LOCATION + etf.getFundid1()+"-"+TimeFomartUtil.getTimeAsString() + ".txt", buffer.toString().getBytes());
		}
	}

	/**
	 * 以Excel格式文件保存
	 */
	public void saveETFAsExcel() {
		if (etfs.size() == 0)
			loadETFByIni();
		Iterator<String> iterator = etfs.keySet().iterator();
		while (iterator.hasNext()) {
			String next = iterator.next();
			ETF etf = etfs.get(next);
			List<StockETF> list = etf.getStockList();
			// wb,对应一个内存中的excel文档
			HSSFWorkbook wb = new HSSFWorkbook();
			// sheet创建一个工作页
			HSSFSheet sheet = wb.createSheet("jzh" + 0);
			sheet.setDefaultColumnWidth(15);
			String[] s = { "证券代码", "证券简称 ", "股票数量（股）", "股票最新市值", "股票权重" };
			// header
			HSSFRow row = sheet.createRow(0);
			for (int x = 0; x < s.length; x++) {

				// 设置行的高度
				// row.setHeight((short) 500);
				HSSFCell cell = row.createCell(x);
				// cell.setEncoding(HSSFCell.ENCODING_UTF_16);
				cell.setCellValue(s[x]);
				// cell.setCellStyle(cellStyle);
			}
			short rowNum = 1;
			int cloNum = 0;
			float total = 0;
			int currentClo = 0;
			for (StockETF stockETF : list) {
				 row = sheet.createRow(rowNum);

				HSSFCell cell = row.createCell(cloNum);
				cell.setCellValue(stockETF.getCode());
				cloNum++;

				HSSFCell cell1 = row.createCell(cloNum);
				cell1.setCellValue(stockETF.getName());
				cloNum++;

				HSSFCell cell2 = row.createCell(cloNum);
				cell2.setCellValue(stockETF.getNumber());
				cloNum++;

				HSSFCell cell3 = row.createCell(cloNum);
				float worth = stockETF.getWorth();
				cell3.setCellValue(worth);
				cloNum++;

				total += worth;
				rowNum++;
				if (currentClo == 0) {
					currentClo = cloNum;
				}
				cloNum = 0;

			}

			for (int i = 1; i < rowNum; i++) {
				row = sheet.getRow(i);
				HSSFCell cell = row.createCell(currentClo);
				cell.setCellValue(row.getCell(currentClo - 1).getNumericCellValue() / total);

			}
			// ExportFileUtil.ExportExcel(DEFAULT_LOCATION + etf.getFundid1() +
			// ".xls", buffer.toString().getBytes());
			try {
				FileOutputStream outputStream = new FileOutputStream(DEFAULT_LOCATION + etf.getFundid1()+"-"+TimeFomartUtil.getTimeAsString() + ".xls");
				wb.write(outputStream);
				outputStream.close();

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 根据配置文件，分析处理各个ETF,加载到电脑内存中
	 */
	private static boolean loadETFByIni() {
		HashMap<String, String> urlMap = ConfigLoader.loadConfig("etfURL.ini");
		HashMap<String, String> marketMap = ConfigLoader.loadConfig("market.ini");
		HashMap<String, String> marketMap_300 = ConfigLoader.loadConfig("300etfmarket.ini");
		Iterator<String> cfgit = urlMap.keySet().iterator();

		while (cfgit.hasNext()) {
			String next = cfgit.next();
			String url = urlMap.get(next);
			url = dealURL(url);
			if (CheckNetUtil.checkNet(url)) {// 网络检查，超过两秒表明网络不可用

				ETF etf = ETFLoader.load(url);
				etfs.put(etf.getFundid1(), etf);
				List<StockETF> list = etf.getStockList();// etf包含的股票

				// 查询价格 
				for (StockETF stockETF : list) {
					String type = marketMap.get(next);
					if (next.equals("510300"))
						type = marketMap_300.get(stockETF.getCode());
					//float price = QueryStockUtil.queryPriceByCode(stockETF.getCode(), type);
					float price = StockQueryUtil.queryLastPriceByCode(stockETF.getCode(), type);
					stockETF.setCurrentPrice(price);// 设置股票价格
				}
			} else {
				// todo 无法访问
			}
			// exportToTxt(etf);
		}
		return true;
	}

	private static String dealURL(String url) {
		if (url.contains("ETF_TYPE="))
			return url;
		return url + TimeFomartUtil.getTimeAsString()+ ".txt";
	}

	public static void main(String[] args) {
		ETFTool etfTool = new ETFTool();
		etfTool.saveETFAsExcel();
	}

}
